from PyQt6.QtCore import Qt, pyqtSignal, QRectF
from PyQt6.QtGui import QPainter, QIntValidator
from PyQt6.QtWidgets import QWidget, QDialog, QGridLayout, QLabel, QLineEdit, QDialogButtonBox

from gui.utils import FLAG_ALIGN_CENTER
from gui.utils.size import TOOL_WIDTH, MSG_HEIGHT, WINDOW_WIDTH, RESOURCE_HEIGHT, ZONING_SIZE, FILTER_HEIGHT
from state.game_state import GameState
from utils.event_bus import EventBus

TOOL_NAMES = (
    '科研比例',
    '装备配置'
)


class PanelTool(QWidget):
    def __init__(self, state: GameState, parent=None):
        super().__init__(parent)

        self.h = MSG_HEIGHT / 2
        self.item_height = self.h / len(TOOL_NAMES)
        self.state: GameState = state

        rect = QRectF(WINDOW_WIDTH - TOOL_WIDTH, RESOURCE_HEIGHT + ZONING_SIZE + FILTER_HEIGHT, TOOL_WIDTH, self.h)
        self.setGeometry(rect.toRect())

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setPen(Qt.GlobalColor.black)
        painter.setBrush(Qt.GlobalColor.white)
        for index, tool in enumerate(TOOL_NAMES):
            rect = QRectF(0, index * self.item_height, TOOL_WIDTH, self.item_height)
            painter.drawRect(rect)
            painter.drawText(rect, FLAG_ALIGN_CENTER, tool)

    def mouseReleaseEvent(self, a0):
        index = a0.pos().y() // self.item_height
        if index == 0:
            self.dialog_tech_rate()

    def dialog_tech_rate(self):
        dialog = QDialog(self)
        dialog.setWindowTitle('设置科研比例')

        layout = QGridLayout()
        label_physics = QLabel('军工')
        label_engineer = QLabel('民用')
        label_beyond = QLabel('超越')

        edit_physics = QLineEdit('3', dialog)
        edit_physics.setValidator(QIntValidator())
        edit_engineer = QLineEdit('3', dialog)
        edit_engineer.setValidator(QIntValidator())
        edit_beyond = QLineEdit('4', dialog)
        edit_beyond.setValidator(QIntValidator())

        layout.addWidget(label_physics, 0, 0)
        layout.addWidget(edit_physics, 0, 1)

        layout.addWidget(label_engineer, 1, 0)
        layout.addWidget(edit_engineer, 1, 1)

        layout.addWidget(label_beyond, 2, 0)
        layout.addWidget(edit_beyond, 2, 1)

        btn = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)
        layout.addWidget(btn, 3, 1)

        def __submit():
            p, e, b = int(edit_physics.text()), int(edit_engineer.text()), int(edit_beyond.text())
            total = p + e + b
            rp, re, rb = p / total, e / total, e / total
            int_p = int(100 * rp)
            int_e = int(100 * re)
            int_b = 100 - int_p - int_e
            EventBus.publish('update_tech_rate', f'{int_p},{int_e},{int_b}')
            dialog.close()

        btn.clicked.connect(__submit)

        dialog.setLayout(layout)
        dialog.show()
